package com.example.work.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.work.entity.Dbhosp;
import com.example.work.entity.TbCheckHosp;
import com.example.work.service.IDbHospService;
import com.example.work.service.IHospService;
import com.example.work.utils.R;
import com.example.work.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: javaLiuwb
 * @date: 2024-11-25 19:30
 * @description:
 */
@RestController
@RequestMapping("/dbhosp")
public class DbHospController {

    @Autowired
    private IDbHospService dbHospService;

    @RequestMapping("/list")
    public R page(@RequestParam(required = false) String hosp_name,
                  @RequestParam(required = false) Integer delete_flag,
                  @RequestParam(value = "current", defaultValue = "1") Integer current,
                  @RequestParam(value = "size", defaultValue = "10") Integer size) {

        QueryWrapper<Dbhosp> queryWrapper = new QueryWrapper<>();
        if (hosp_name != null) {
            queryWrapper.like("hosp_name", hosp_name); // 模糊查询
        }
        if (delete_flag != null) {
            queryWrapper.eq("delete_flag", delete_flag); // 精确查询
        }

        // 创建分页对象
        Page<Dbhosp> page = new Page<>(current, size);

        // 使用 MyBatis-Plus 提供的分页查询方法
        Page<Dbhosp> dbhospPage = dbHospService.page(page, queryWrapper);

        // 封装结果
        Map<String, Object> map = new HashMap<>();
        map.put("total", dbhospPage.getTotal()); // 总记录数
        map.put("pages", dbhospPage.getPages()); // 总页数
        map.put("current", dbhospPage.getCurrent()); // 当前页码
        map.put("size", dbhospPage.getSize()); // 每页记录数
        map.put("records", dbhospPage.getRecords()); // 当前页数据

        return R.ok(map);
    }
    //根据名字  deleteflag查找医院
    @RequestMapping("/list/{hosp_name}/{delete_flag}")
    public R listByName(@PathVariable(value = "hosp_name")String hosp_name,
                        @PathVariable(value = "delete_flag")Integer delete_flag
                        ){

        QueryWrapper<Dbhosp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hosp_name", hosp_name).or().eq("delete_flag", delete_flag);
        List<Dbhosp> dbhospList = dbHospService.list(queryWrapper);
        Map<String,Object> map=new HashMap<>();
        map.put("dbhospListByNameOrDelete",dbhospList);
        return R.ok(map);
    }




    //添加
    @RequestMapping("/save")
    public R save(@RequestHeader("Authorization") String authorizationHeader,@RequestBody Dbhosp dbhosp){
        //System.out.println(dbCheckCategory.toString());
        String userName = TokenUtils.getUserNameFromToken(authorizationHeader);
        if(dbhosp.getHospId()==null){
            Date date = new Date();
            dbhosp.setCreateTime(date);
            dbhosp.setUpdateTime(date);
            dbhosp.setCreateBy(userName);
            dbHospService.save(dbhosp);
        }else {
            Date date = new Date();
            dbhosp.setUpdateTime(date);
            dbHospService.saveOrUpdate(dbhosp);
        }
        return R.ok();
    }

    //删除
    @RequestMapping("/delete/{hosp_id}")
    public R delete(@PathVariable(value = "hosp_id") String hosp_id) {
        // 使用 RemoveWrapper 构造删除条件
        QueryWrapper<Dbhosp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hosp_id", hosp_id);

        // 调用服务层的删除方法
        boolean isDeleted = dbHospService.remove(queryWrapper);

        // 根据删除结果返回响应
        if (isDeleted) {
            return R.ok("删除成功");
        } else {
            return R.error("删除失败，可能记录不存在");
        }
    }

    @PutMapping("/update/{hospId}")
    public R updateHospById(
            @PathVariable("hospId") String hospId, // 使用 @PathVariable 动态路径参数
            @RequestBody Dbhosp dbhosp // 使用 @RequestBody 接收 JSON 数据
    )
    {
        // 打印接收到的 ID
        System.out.println("接收到的医院 ID：" + hospId);
        // 检查路径中的 hospId 是否为空
        if (hospId == null || hospId.isEmpty()) {
            return R.error("医院 ID 不能为空");
        }
        // 检查请求体中的数据是否完整
        if (dbhosp == null) {
            return R.error("请求体不能为空");
        }
        // 设置 Dbhosp 对象的 hospId（确保请求体中的 hospId 与路径参数一致）
        dbhosp.setHospId(hospId);
        // 调用服务层更新方法
        boolean isUpdated = dbHospService.updateHospById(dbhosp);
        // 返回操作结果
        if (isUpdated) {
            return R.ok("修改成功");
        } else {
            return R.error("修改失败");
        }
    }
    @GetMapping("/all")
    public R getAllHosp() {
        Map<String,Object> map=new HashMap<>();
        map.put("hospList",dbHospService.list());
        return R.ok(map);
    }


}
